package com.javalaoniu.tool.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


/**
 * AES加解密工具类
 *
 * @author liangxn
 */
public class AESEncryptUtil {

    /**
     * SecureRandom类的seed，可以改为自己的字符串
     */
    private static final String RANDOM_SEED = "seed-abcxyz-123-456";

    private AESEncryptUtil() {}

    /**
     * 加密方法
     */
    public static String encrypt(String content) {
        // 待加密的内容
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);
        byte[] data = new byte[0];
        try {
            data = cipher(contentByte, Cipher.ENCRYPT_MODE);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data), StandardCharsets.UTF_8);
    }

    /**
     * 解密方法
     */
    public static String decrypt(String content) {
        byte[] decodeContent = Base64.decodeBase64(content);
        byte[] data = new byte[0];
        try {
            data = cipher(decodeContent, Cipher.DECRYPT_MODE);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return new String(data, StandardCharsets.UTF_8);
    }

    /**
     * 加解密计算器
     *
     * @param content 要加密的内容
     * @param mode    计算模式（本工具类用到Cipher.ENCRYPT_MODE、Cipher.DECRYPT_MODE这两个）
     * @return
     */
    private static byte[] cipher(byte[] content, int mode) throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        if (content == null) {
            throw new NullPointerException("content为空");
        }
        if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) {
            throw new IllegalArgumentException("mode非法");
        }

        // AES密钥生成器实例
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        // 安全随机数工具，创建SHA1PRNG随机算法的实例
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // 设置种子
        random.setSeed(AESEncryptUtil.RANDOM_SEED.getBytes(StandardCharsets.UTF_8));
        // 初始化密钥生产器
        keygen.init(128, random);
        // 生成原始对称密钥
        SecretKey secretKey = keygen.generateKey();
        // 获得原始对称密钥的字节数组
        byte[] secretKeyByte = secretKey.getEncoded();

        // 生成AES密钥
        SecretKey key = new SecretKeySpec(secretKeyByte, "AES");
        // 创建加密器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化加密器
        cipher.init(mode, key);

        // 数据加密
        return cipher.doFinal(content);
    }
}
